<script setup>
import { introApi } from "@/services/index";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { nextTick, ref, watch, onMounted } from "vue";
import { appInfo, loginSwitch } from "@/services/user";
import topNav from "../../components/topNav.vue";
import { operation } from "@/utils/num.js";
import {
  appOrderCreate,
  getProductByBarCode,
  appOrderDetail,
  getOrderRefundCalc,
  getPayRefund,
} from "@/services/cashier";

const goodsList = ref([]);
const payNum = ref(0);
const payPrice = ref(0);
const oldPayPrice = ref(0);
const goodsListNo = ref([]);
const sand_code = ref("");
const id = ref("");
const orderDetail = ref({});

onShow(() => {
  if (uni.getStorageSync("barCode")) {
    sand_code.value = uni.getStorageSync("barCode");
    getProductByBarCodeFun();
  }
  //   console.log(goodsList.value);
  //   console.log(goodsListNo.value);
});

onLoad((e) => {
  id.value = e.id ? e.id : "";
  // if (uni.getStorageSync("goods")) {
  //   goodsList.value = JSON.parse(uni.getStorageSync("goods"));
  //   goodsList.value.forEach((item) => {
  //     if (item.weight && item.weight > 0) {
  //       item.price = item.price ? item.price : item.totalPrice;
  //       payNum.value = payNum.value + item.orderNum;
  //       payPrice.value = operation(
  //         payPrice.value,
  //         operation(item.totalPrice, item.orderNum, 2, "multiply"),
  //         2,
  //         "add"
  //       );
  //     } else {
  //       item.price = item.price ? item.price : item.totalPrice;
  //       payNum.value = payNum.value + item.orderNum;
  //       payPrice.value = operation(
  //         payPrice.value,
  //         operation(
  //           item.orderNum,
  //           item.price ? item.price : item.totalPrice,
  //           2,
  //           "multiply"
  //         ),
  //         2,
  //         "add"
  //       );
  //     }
  //   });
  // }
  // if (uni.getStorageSync("goodsNo")) {
  //   goodsListNo.value = JSON.parse(uni.getStorageSync("goodsNo"));
  //   goodsListNo.value.forEach((item) => {
  //     payNum.value = payNum.value + item.orderNum;
  //     payPrice.value = operation(
  //       payPrice.value,
  //       operation(item.orderNum, item.salePrice, 2, "multiply"),
  //       2,
  //       "add"
  //     );
  //   });
  // }
  // if (goodsList.value.length <= 0 && goodsListNo.value.length <= 0) {
  //   uni.redirectTo({ url: "/pages/index/index" });
  // }
  // console.log(goodsList.value);
  getAppOrderDetail();
});

const getAppOrderDetail = async () => {
  let res = await appOrderDetail({
    id: id.value,
  });

  let price = 0;
  let num = 0;
  res.data.details.forEach((element) => {
    element.totalPrice = operation(
      element.oriPrice,
      element.orderNum,
      2,
      "multiply"
    );
    element.maxPrice = operation(
      element.oriPrice,
      element.orderNum,
      2,
      "multiply"
    );
    element.returnNum = element.orderNum;
    num = operation(num, element.orderNum, 2, "add");
    price = operation(
      price,
      operation(element.orderNum, element.oriPrice, 2, "multiply"),
      2,
      "add"
    );
  });
  payPrice.value = price;
  payNum.value = num;

  orderDetail.value = res.data;
  // getPrice();
  // openList.value = res.data.datas;
};

const getPrice = async () => {
  let arr = orderDetail.value.details.filter((item) => {
    return item.returnNum > 0;
  });
  if (arr.length > 0) {
    let res = await getOrderRefundCalc({
      id: id.value,
      products: arr,
    });
    payPrice.value = res.data.returnAmount;
  } else {
    payPrice.value = 0;
  }
};

const saveFun = () => {
  console.log("保存");
  //   console.log(form.value);
  // console.log(fileList.value[0].content);
  //   formMode.value.submit();
};
const value = ref(0);
const show = ref(false);

// 定义方法
const valChange = (e) => {
  console.log(e);

  let num = 0;
  let price = 0;

  setTimeout(() => {
    orderDetail.value.details.forEach((item) => {
      // num = num + item.returnNum;
      item.totalPrice = operation(item.oriPrice, item.returnNum, 2, "multiply");
      num = operation(num, item.returnNum, 2, "add");
      price = operation(
        price,
        operation(item.returnNum, item.oriPrice, 2, "multiply"),
        2,
        "add"
      );
    });
    // goodsListNo.value.forEach((item) => {
    //   num = num + item.orderNum;
    //   price = operation(
    //     price,
    //     operation(item.orderNum, item.salePrice, 2, "multiply"),
    //     2,
    //     "add"
    //   );
    // });
    // getPrice();
    payPrice.value = price;
    payNum.value = num;
    // uni.setStorageSync("goods", JSON.stringify(goodsList.value));
    // uni.setStorageSync("goodsNo", JSON.stringify(goodsListNo.value));

    if (payNum.value == 0) {
      popupshow.value = false;
    }
  }, 100);
};
const confirmModal = () => {
  goodsList.value.forEach((item) => {
    item.orderNum = 0;
  });
  payNum.value = 0;
  show.value = false;

  uni.redirectTo({ url: "/pages/cashier/goods/index" });
};
const rightClick = () => {
  console.log("rightClick");
};

const leftClick = () => {
  console.log("leftClick");
};
// const goPay = () => {
//   uni.navigateTo({
//     url: "/pages/cashier/goods_confirm/index",
//   });
// };
//清空
const clearFun = () => {
  show.value = true;
};

//支付
const isPay = ref(false);

const goPay = async () => {
  show.value = false;
  passwordShow.value = true;
};

const keyWord = ref(null);
const priceValue = ref(0);
const selectType = ref(1);
const selectTypeIndex = ref(0);
const selectItemObj = ref({});

const selectNumIndex = ref(-1);
const del = (e) => {
  if (e == 0) {
    selectNumIndex.value = selectNumIndex.value - 1;
  } else if (e == 1) {
    selectNumIndex.value = selectNumIndex.value + 1;
  }
};
const keyWordItem = (index) => {
  selectNumIndex.value = index;
};
const inp = (e) => {};

//金额键盘

const hide = () => {
  // if (num.value > 0) {
  // } else {
  //   jsnum.value = 0;
  // }
  // isPayShow.value = false;
  keyWord.value.close();
};
const confirm = async () => {
  if (priceValue.value <= 0) {
    uni.showToast({
      title: "请输入正确金额",
      icon: "none",
    });
    return;
  }

  if (
    priceValue.value > orderDetail.value.details[selectTypeIndex.value].maxPrice
  ) {
    uni.showToast({
      title:
        "最高退款总价为" +
        orderDetail.value.details[selectTypeIndex.value].maxPrice,
      icon: "none",
    });
    return;
  }

  orderDetail.value.details[selectTypeIndex.value].totalPrice = Number(
    priceValue.value
  );
  let num = 0;
  let price = 0;

  orderDetail.value.details.forEach((item) => {
    console.log(item);

    num = num + item.returnNum;
    price = operation(price, Number(item.totalPrice), 2, "add");
  });
  payPrice.value = price;
  payNum.value = num;

  // getcomputeBrokerage(Number(num.value));
  // productDataNo.value[selectNo.value].salePrice = Number(priceValue.value);
  // productDataNo.value[selectNo.value].orderNum = 1;

  // payPrice.value = operation(
  //   payPrice.value,
  //   Number(priceValue.value),
  //   2,
  //   "add"
  // );
};
const closePay = () => {
  // isPayShow.value = false;
  keyWord.value.close();
};
const priceClick = (item, index, type) => {
  if (item.weight && item.weight > 0) return;
  selectItemObj.value = item;
  selectTypeIndex.value = index;
  selectType.value = type;
  priceValue.value = String(item.totalPrice);
  // console.log("item", selectTypeIndex.value, selectType.value);
  // if (type == 1) {
  //   if (item.weight && item.weight > 0) {
  //     priceValue.value = String(item.totalPrice);
  //     if (item.oldprice && item.oldprice > 0) {
  //     } else {
  //       item.oldprice = item.totalPrice;
  //     }
  //   } else {
  //     priceValue.value = String(item.price);

  //     if (item.oldprice && item.oldprice > 0) {
  //     } else {
  //       item.oldprice = item.price;
  //     }
  //   }
  //   console.log("item", item, goodsList.value);
  // }
  // if (type == 2) {
  //   priceValue.value = String(item.salePrice);
  // }
  selectNumIndex.value = -1;
  keyWord.value.open();
};

const addUitCode = () => {
  // #ifdef H5
  uni.navigateTo({
    url: "/pages/code_sand/index?type=addBarCode",
  });
  // #endif
  // #ifndef H5
  // 允许从相机和相册扫码
  uni.scanCode({
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true,
    autoZoom: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      sand_code.value = res.result;
      getProductByBarCodeFun();
    },
  });
  // #endif
};

const getProductByBarCodeFun = async () => {
  try {
    // let res = await getProductByBarCode({ barCode: "2200269012341" });
    let res = await getProductByBarCode({ barCode: sand_code.value });

    if (res.code == 200) {
      uni.removeStorageSync("barCode");
      goodsList.value.push(res.data);

      payNum.value = payNum.value + res.data.orderNum;
      payPrice.value = operation(
        payPrice.value,
        operation(
          res.data.orderNum,
          res.data && res.data.weight && res.data.weight > 0
            ? res.data.totalPrice
            : res.data.price,
          2,
          "multiply"
        ),
        2,
        "add"
      );
      if (uni.getStorageSync("barCode")) {
        uni.removeStorageSync("barCode");
      }
    } else {
      uni.showToast({
        title: res.message,
        icon: "none",
      });
      if (uni.getStorageSync("barCode")) {
        uni.removeStorageSync("barCode");
      }
    }
  } catch (e) {
    uni.showToast({
      title: e.message,
      icon: "none",
    });
    if (uni.getStorageSync("barCode")) {
      uni.removeStorageSync("barCode");
    }
  }
};

const isUp = ref(false);
const passwordShow = ref(false);
const isshowpassword = ref(false);
const password = ref("");
const qrUpSign = async () => {
  if (!password.value) {
    uni.showToast({
      title: "请输入登录密码",
      icon: "none",
    });
    return;
  }

  if (isUp.value) {
    return;
  }
  isUp.value = true;
  let arr = [];
  orderDetail.value.details.forEach((item) => {
    arr.push({
      id: item.id,
      productId: item.productId,
      returnNum: item.returnNum,
    });
  });

  try {
    let res = await getPayRefund({
      id: id.value,
      products: arr,
      password: password.value,
      transAmt: payPrice.value,
    });
    if (res.code == 200) {
      uni.showToast({
        title: "退款成功",
        icon: "success",
        mask: true,
      });
      let pages = getCurrentPages();

      // 获取页面栈的长度，即页面跳转层级
      let level = pages.length;

      if (level > 1) {
        uni.navigateBack();
      } else {
        uni.redirectTo({
          url: "/pages/cashier/sales_order/index",
        });
      }
      // optionDet.value.status = 12;
      isUp.value = false;
      passwordShow.value = false;
      // getAppProductQuery(1);
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none",
      });
      isUp.value = false;
      passwordShow.value = false;
    }

    console.log(res);
  } catch (e) {
    uni.showToast({
      title: e.msg,
      icon: "none",
    });
    isUp.value = false;
    passwordShow.value = false;
  }
};
const showRefund = () => {
  if (payNum.value <= 0) {
    return uni.showToast({
      title: "请选择退款商品",
      icon: "none",
    });
  }
  show.value = true;
};
</script>

<template>
  <view class="bg">
    <jia-PayKeyboard
      :confirmStyle="{ backgroundColor: '#1679FB' }"
      class="keyWord-index"
      :overlayClose="true"
      ref="keyWord"
      v-model="priceValue"
      :sclectItem="selectNumIndex"
      @input="inp"
      @del="del"
      @confirm="confirm"
      @hide="hide"
      style="z-index: 1000"
    >
      <view class="PayKeyboard-k">
        <view class="icon-top">
          <up-icon
            @click="closePay"
            name="close"
            color="#86909C"
            size="30rpx"
          ></up-icon
        ></view>
        <view class="PayKeyboard-k-title"
          ><text>{{ selectItemObj.productName }}</text>
        </view>
        <view class="link-to"></view>
        <view class="PayKeyboard-k-num">
          <view class="PayKeyboard-k-num-title">退款金额</view>
          <view class="PayKeyboard-k-num-input">
            <up-form labelPosition="left" ref="form1" labelWidth="0">
              <up-form-item
                label=" "
                borderBottom
                ref="item1"
                @click="keyWordItem(-1)"
              >
                <view class="PayKeyboard-k-num-input-text">
                  <view
                    class="num-view"
                    v-for="(item, index) in priceValue"
                    :key="index"
                    @click.stop="keyWordItem(index)"
                    ><view
                      class="input_lin"
                      v-if="selectNumIndex == index"
                    ></view
                    >{{ item }}</view
                  >
                  <view class="input_lin" v-if="selectNumIndex == -1"></view>
                </view>

                <template #right>
                  <text>元</text>
                </template>
              </up-form-item>
            </up-form>
          </view>
        </view>
      </view>
    </jia-PayKeyboard>

    <topNav
      :title="'销售单退款'"
      @save="saveFun"
      :border="true"
      rType="save"
    ></topNav>
    <view class="content">
      <view v-for="(item, index) in orderDetail.details" :key="index">
        <view class="content-item">
          <view class="content-item-left">
            <image
              src="https://cloud-erp.yibaitao.cn/0d2f4178-7754-4686-9213-b174f745258b.png"
              mode="scaleToFill"
          /></view>
          <view class="content-item-right">
            <view class="content-item-right-title">
              <text>{{ item.productName }}</text>
            </view>
            <view class="content-item-right-num">
              <view class="content-item-right-num-left"><text></text> </view>
              <view class="content-item-right-num-right">
                <up-number-box
                  v-model="item.returnNum"
                  @change="valChange"
                  min="0"
                  :max="item.orderNum"
                ></up-number-box>
              </view>
            </view>
            <!-- @click="priceClick(item, index, 2)" -->
            <view class="content-item-right-price"
              ><text>¥</text>{{ item.oriPrice }} &nbsp; <text>退款总金额:¥</text
              >{{ item.totalPrice
              }}<up-icon
                name="edit-pen"
                color="#ff5722"
                size="42rpx"
                @click="priceClick(item, index, 2)"
              ></up-icon>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view style="width: 100%; height: 150rpx"></view>
  </view>

  <view class="bt_form" v-permission="['shop:order:create']">
    <view class="bt_form_k">
      <view class="bt_form_k_left">
        <view class="price"
          ><text>¥</text>{{ payPrice }}
          <view class="price-num">已选{{ payNum }}件</view></view
        >
        <!-- <text class="bt_form_k_left_clear" @click="clearFun">清空</text> -->
      </view>
      <view class="bt_pay" @click="showRefund">确定退款</view>
    </view>
  </view>

  <up-modal
    :show="show"
    title="退款确认"
    :showCancelButton="true"
    confirmText="确认"
    cancelText="取消"
    @cancel="show = false"
    @confirm="goPay"
    width="540rpx"
    cancelColor="#1679FB"
    confirmColor="#1679FB"
  >
    <view class="slot-content" style="color: #4e5969">
      <rich-text
        :nodes="'共退' + payNum + '件, 退款' + payPrice + '元'"
      ></rich-text>
    </view>
  </up-modal>

  <up-popup
    :show="passwordShow"
    round="15"
    mode="center"
    @close="passwordShow = false"
  >
    <view class="pop-content">
      <view class="pop-content-info">
        <view class="title"> 请输入登录密码校验 </view>
        <view class="content-to">
          <up-input
            class="input"
            placeholder="请输入登录密码"
            suffixIcon="map-fill"
            v-model="password"
            suffixIconStyle="color: #909399"
            :type="!isshowpassword ? 'password' : 'text'"
          >
            <!-- eye-off -->
            <template #suffix>
              <up-icon
                @click="isshowpassword = !isshowpassword"
                :name="!isshowpassword ? 'eye-fill' : 'eye-off'"
                color="#86909C"
                size="36rpx"
              ></up-icon>
            </template>
          </up-input>
        </view>
      </view>

      <view class="btns">
        <view class="btns-bt" @click="passwordShow = false">取消</view>

        <view class="btns-qd" @click="qrUpSign">确定</view></view
      >
    </view>
  </up-popup>
</template>

<style lang="scss" scoped>
@import "index.scss";
</style>
